package com.uduemc.biso.node.web.service.html.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.github.pagehelper.PageInfo;
import com.uduemc.biso.node.core.common.entities.SiteSearchPage;
import com.uduemc.biso.node.core.common.hostconfig.SearchPageConfig;
import com.uduemc.biso.node.core.common.hostconfig.SearchPageTextConfig;
import com.uduemc.biso.node.core.common.sysconfig.ArticleSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.DownloadSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.FaqSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.ProductSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.articlesysconfig.ArticleSysListConfig;
import com.uduemc.biso.node.core.common.sysconfig.downloadsysconfig.DownloadSysListConfig;
import com.uduemc.biso.node.core.common.sysconfig.faqsysconfig.FaqSysListConfig;
import com.uduemc.biso.node.core.common.sysconfig.productsysconfig.ProductSysListConfig;
import com.uduemc.biso.node.core.entities.SCategories;
import com.uduemc.biso.node.core.entities.SDownloadAttr;
import com.uduemc.biso.node.core.entities.SFaq;
import com.uduemc.biso.node.core.entities.SSystem;
import com.uduemc.biso.node.core.entities.custom.Article;
import com.uduemc.biso.node.core.entities.custom.Download;
import com.uduemc.biso.node.core.entities.custom.ProductDataTableForList;
import com.uduemc.biso.node.core.entities.custom.SearchSystem;
import com.uduemc.biso.node.core.utils.SystemConfigUtil;
import com.uduemc.biso.node.web.component.RequestHolder;
import com.uduemc.biso.node.web.component.SiteUrlComponent;
import com.uduemc.biso.node.web.component.html.HSearchArticleItemListUdin;
import com.uduemc.biso.node.web.component.html.HSearchDownloadItemListUdin;
import com.uduemc.biso.node.web.component.html.HSearchFaqItemListUdin;
import com.uduemc.biso.node.web.component.html.HSearchProductItemListUdin;
import com.uduemc.biso.node.web.entities.AccessPage;
import com.uduemc.biso.node.web.service.ConfigSiteService;
import com.uduemc.biso.node.web.service.ContentService;
import com.uduemc.biso.node.web.service.byfeign.CategoryService;
import com.uduemc.biso.node.web.service.byfeign.DownloadService;
import com.uduemc.biso.node.web.service.byfeign.SearchService;
import com.uduemc.biso.node.web.service.html.BasicUdinService;
import com.uduemc.biso.node.web.service.html.HSearchPageService;
import com.uduemc.biso.node.web.utils.AssetsResponseUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Service
public class HSearchPageServiceImpl implements BasicUdinService, HSearchPageService {

    @Resource
    private RequestHolder requestHolder;

    @Resource
    private SearchService searchServiceImpl;

    @Resource
    private SiteUrlComponent siteUrlComponent;

    @Resource
    private CategoryService categoryServiceImpl;

    @Resource
    private DownloadService downloadServiceImpl;

    @Resource
    private HSearchArticleItemListUdin hSearchArticleItemListUdin;

    @Resource
    private HSearchProductItemListUdin hSearchProductItemListUdin;

    @Resource
    private HSearchDownloadItemListUdin hSearchDownloadItemListUdin;

    @Resource
    private HSearchFaqItemListUdin hSearchFaqItemListUdin;

    @Resource
    private ContentService contentServiceImpl;

    @Resource
    private ConfigSiteService configSiteServiceImpl;

    @Override
    public StringBuilder html() {
        long hostId = requestHolder.getHostId();
        long siteId = requestHolder.getSiteId();
        try {
            return html(hostId, siteId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new StringBuilder();
    }

    @Override
    public StringBuilder html(Long hostId, Long siteId) throws Exception {
        StringBuilder result = new StringBuilder();
        result.append("<div class=\"row\">");
        result.append("<div class=\"wrap-content-in\">");
        // 搜索框
        result.append(searchHtml(hostId, siteId));

        AccessPage accessPage = requestHolder.getAccessPage();
        SiteSearchPage siteSearchPage = accessPage.getSitePage().getSiteSearchPage();
        long sPageId = siteSearchPage.getSPageId();
        String keyword = siteSearchPage.getKeyword();
        int pageNum = siteSearchPage.getPageNum();
        int pageSize = siteSearchPage.getPageSize();
        if (StrUtil.isBlank(keyword)) {
            // 没有输入检索内容
            result.append(noSearchHtml());
        } else {
            List<SearchSystem> listSearchSystem = null;
            try {
                listSearchSystem = searchServiceImpl.allSystemByHolder(keyword);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (CollUtil.isEmpty(listSearchSystem)) {
                // 没有搜索到结果
                result.append(noDataSearchHtml());
            } else {
                SearchSystem searchSystem = sPageId == 0 ? CollUtil.getFirst(listSearchSystem) : CollUtil.findOne(listSearchSystem, item -> {
                    return item.getPageId() != null && item.getPageId().longValue() == sPageId;
                });
                if (searchSystem == null) {
                    // 没有搜索到结果
                    result.append(noDataSearchHtml());
                } else {
                    // 搜索左侧系统数据
                    result.append(searchSystemHtml(hostId, siteId, listSearchSystem, searchSystem));
                    // 搜索右侧系统内的数据内容
                    result.append(searchListHtml(hostId, siteId, searchSystem, pageNum, pageSize));
                }
            }
        }

        result.append("</div>");
        result.append("</div>");
        return result;
    }

    @Override
    public StringBuilder searchHtml(Long hostId, Long siteId) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
        SearchPageConfig searchPageConfig = configSiteServiceImpl.searchPageConfig(hostId, siteId);
        SearchPageTextConfig searchPageTextConfig = searchPageConfig.getText();

        String siteSearch = searchPageTextConfig.getSiteSearch();
        String searchContent = searchPageTextConfig.getSearchContent();
        String searchButton = searchPageTextConfig.getSearchButton();

        String alertBtn = searchPageTextConfig.getAlertBtn();
        String alertTitle = searchPageTextConfig.getAlertTitle();
        String emptyMsg = searchPageTextConfig.getEmptyMsg();

        AccessPage accessPage = requestHolder.getAccessPage();
        SiteSearchPage siteSearchPage = accessPage.getSitePage().getSiteSearchPage();
        String keyword = siteSearchPage.getKeyword();

        StringBuilder result = new StringBuilder();

        result.append("<div class=\"w-search-top clearfix\">");
        result.append("<div class=\"w-search-tit\">" + siteSearch + "</div>");
        result.append("<div class=\"w-search-box-r\">");
        result.append("<div class=\"w-searchbox\">");
        result.append("<div class=\"search-w search-defaut-w\">");

        // 弹窗提示内容隐藏分布
        result.append("<input type=\"hidden\" name=\"alertBtn\" value=\"" + alertBtn + "\" />");
        result.append("<input type=\"hidden\" name=\"alertTitle\" value=\"" + alertTitle + "\" />");
        result.append("<input type=\"hidden\" name=\"emptyMsg\" value=\"" + emptyMsg + "\" />");

        result.append("<input type=\"text\" class=\"input-text-w input-search-w\" placeholder=\"" + searchContent + "\" value=\""
                + (StrUtil.isNotBlank(keyword) ? keyword : "") + "\"/>");
        result.append("<div class=\"btn-default-w search-btn-w g-click-search\"><span class=\"btn-inner\">" + searchButton + "</span></div>");
        result.append("</div>");
        result.append("</div>");
        result.append("</div>");
        result.append("</div>");

        return result;
    }

    @Override
    public StringBuilder noSearchHtml() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
        long hostId = requestHolder.getHostId();
        long siteId = requestHolder.getSiteId();
        SearchPageConfig searchPageConfig = configSiteServiceImpl.searchPageConfig(hostId, siteId);
        SearchPageTextConfig searchPageTextConfig = searchPageConfig.getText();
        String noSearch = searchPageTextConfig.getNoSearch();

        StringBuilder result = new StringBuilder();
        result.append("<div class=\"search-empty\" style=\"height:300px;justify-content: center;display: flex;align-items: center;\">");
        result.append(noSearch);
        result.append("</div>");

        return result;
    }

    @Override
    public StringBuilder noDataSearchHtml() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
        long hostId = requestHolder.getHostId();
        long siteId = requestHolder.getSiteId();
        SearchPageConfig searchPageConfig = configSiteServiceImpl.searchPageConfig(hostId, siteId);
        SearchPageTextConfig searchPageTextConfig = searchPageConfig.getText();
        String noDataSearch = searchPageTextConfig.getNoDataSearch();

        StringBuilder result = new StringBuilder();
        result.append("<div class=\"search-empty\" style=\"height:300px;justify-content: center;display: flex;align-items: center;\">");
        result.append(noDataSearch);
        result.append("</div>");

        return result;
    }

    @Override
    public StringBuilder searchSystemHtml(Long hostId, Long siteId, List<SearchSystem> listSearchSystem, SearchSystem curSearchSystem)
            throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
        SearchPageConfig searchPageConfig = configSiteServiceImpl.searchPageConfig(hostId, siteId);
        SearchPageTextConfig searchPageTextConfig = searchPageConfig.getText();
        String searchCenter = searchPageTextConfig.getSearchCenter();

        StringBuilder result = new StringBuilder();
        AccessPage accessPage = requestHolder.getAccessPage();
        SiteSearchPage siteSearchPage = accessPage.getSitePage().getSiteSearchPage();
        String keyword = siteSearchPage.getKeyword();

        // 获取总数据数
        int total = 0;
        StringBuilder li = new StringBuilder();
        for (SearchSystem searchSystem : listSearchSystem) {
            total += searchSystem.getTotal();

            String cur = "";
            if (curSearchSystem.getPageId().longValue() == searchSystem.getPageId().longValue()) {
                cur = "cur";
            }

            String searchHref = siteUrlComponent.getSearchPath(keyword, searchSystem.getPageId());
            li.append("<li class=\"li-parent " + cur + "\" data-pgid=\"" + searchSystem.getPageId() + "\" data-sysid=\"" + searchSystem.getSystemId() + "\">");
            li.append("<div class=\"div-parent\"> ");
            li.append("<a href=\"" + searchHref + "\">" + searchSystem.getPageName() + "<span class=\"num\"> (" + searchSystem.getTotal() + ")</span></a>");
            li.append("<span class=\"menu_simpline_cur\"></span>");
            li.append("</div>");
            li.append("</li>");
        }

        result.append("<div class=\"side_bar\">");
        result.append("<div class=\"w-com-menu w-com-menu-V\">");
        result.append("<div class=\"w-com-menu-in\">");
        result.append("<style type=\"text/css\">");
        result.append("@media (max-width: 767px){");
        result.append(".systitle {position: relative;padding-right: 0.5em !important;}");
        result.append(".w-com-menu .fa{top:9px!important;width:inherit!important;right:0.5em!important;}");
        result.append("}");
        result.append("</style>");
        result.append("<div class=\"systitle\">");
        result.append("<div class=\"systitle-in\">" + searchCenter + "<span class=\"num\"> (" + total + ")</span></div><i class=\"fa icon_menuControl\"></i>");
        result.append("</div>");
        result.append("<ul class=\"ul-parent\">");
        result.append(li);
        result.append("</ul>");
        result.append("</div>");
        result.append("</div>");
        result.append("</div>");

        return result;
    }

    @Override
    public StringBuilder searchListHtml(Long hostId, Long siteId, SearchSystem searchSystem, int page, int size) throws Exception {
        SSystem system = searchSystem.getSystem();
        Long systemTypeId = system.getSystemTypeId();
        StringBuilder result = new StringBuilder();
        if (systemTypeId == null) {
            return result;
        }

        if (systemTypeId.longValue() == 1) {
            result.append(articleSearch(hostId, siteId, searchSystem, page, size));
        } else if (systemTypeId.longValue() == 3) {
            result.append(productSearch(hostId, siteId, searchSystem, page, size));
        } else if (systemTypeId.longValue() == 5) {
            result.append(downloadSearch(hostId, siteId, searchSystem, page, size));
        } else if (systemTypeId.longValue() == 6) {
            result.append(faqSearch(hostId, siteId, searchSystem, page, size));
        }

        return result;
    }

    private StringBuilder faqSearch(Long hostId, Long siteId, SearchSystem searchSystem, int page, int size) throws Exception {
        StringBuilder result = new StringBuilder();
        SSystem system = searchSystem.getSystem();
        Long systemId = system.getId();
        AccessPage accessPage = requestHolder.getAccessPage();
        SiteSearchPage siteSearchPage = accessPage.getSitePage().getSiteSearchPage();
        String keyword = siteSearchPage.getKeyword();

        // 获取系统配置
        FaqSysConfig faqSysConfig = SystemConfigUtil.faqSysConfig(system);
        if (faqSysConfig == null) {
            return result;
        }
        // 通过配置获取 每页显示的产品数量
        FaqSysListConfig list = faqSysConfig.getList();
        if (list != null && list.getPerpage() > 1) {
            size = list.getPerpage();
        }

        // 通过系统数据，获取该系统下的所有分类数据！
        List<SCategories> listSCategories = categoryServiceImpl.getInfosByHostSiteSystemIdAndDefaultOrder(system.getHostId(), system.getSiteId(),
                system.getId());

        PageInfo<SFaq> faqSearchByHolder = searchServiceImpl.faqSearchByHolder(systemId, keyword, page, size);
        List<SFaq> listFaq = faqSearchByHolder != null ? faqSearchByHolder.getList() : null;

        // 过滤富文本中的内容
        if (CollUtil.isNotEmpty(listFaq)) {
            for (SFaq sFaq : listFaq) {
                sFaq.setInfo(contentServiceImpl.filterUEditorContentWithSite(sFaq.getInfo()));
            }
        }

        StringBuilder html = hSearchFaqItemListUdin.html(faqSysConfig, searchSystem.getPage(), listFaq, listSCategories, keyword, page, searchSystem.getTotal(),
                size);
        result.append(AssetsResponseUtil.htmlCompress(html, false));
        return result;
    }

    private StringBuilder downloadSearch(Long hostId, Long siteId, SearchSystem searchSystem, int page, int size) throws Exception {
        StringBuilder result = new StringBuilder();
        SSystem system = searchSystem.getSystem();
        Long systemId = system.getId();
        AccessPage accessPage = requestHolder.getAccessPage();
        SiteSearchPage siteSearchPage = accessPage.getSitePage().getSiteSearchPage();
        String keyword = siteSearchPage.getKeyword();

        // 获取系统配置
        DownloadSysConfig downloadSysConfig = SystemConfigUtil.downloadSysConfig(system);
        if (downloadSysConfig == null) {
            return result;
        }
        // 通过配置获取 每页显示的产品数量
        DownloadSysListConfig list = downloadSysConfig.getList();
        if (list != null && list.getPerpage() > 1) {
            size = list.getPerpage();
        }

        // 通过系统数据，获取该系统下的所有分类数据！
        List<SCategories> listSCategories = categoryServiceImpl.getInfosByHostSiteSystemIdAndDefaultOrder(system.getHostId(), system.getSiteId(),
                system.getId());

        List<SDownloadAttr> listSDownloadAttr = downloadServiceImpl.getAttrInfosByHostSiteSystemId(hostId, siteId, systemId);

        PageInfo<Download> downloadSearchByHolder = searchServiceImpl.downloadSearchByHolder(systemId, keyword, page, size);
        StringBuilder html = hSearchDownloadItemListUdin.html(downloadSysConfig, searchSystem.getPage(), listSDownloadAttr, downloadSearchByHolder.getList(),
                listSCategories, keyword, page, searchSystem.getTotal(), size);
        result.append(AssetsResponseUtil.htmlCompress(html, false));
        return result;
    }

    private StringBuilder productSearch(Long hostId, Long siteId, SearchSystem searchSystem, int page, int size) throws Exception {
        StringBuilder result = new StringBuilder();
        SSystem system = searchSystem.getSystem();
        Long systemId = system.getId();
        AccessPage accessPage = requestHolder.getAccessPage();
        SiteSearchPage siteSearchPage = accessPage.getSitePage().getSiteSearchPage();
        String keyword = siteSearchPage.getKeyword();

        // 获取系统配置
        ProductSysConfig productSysConfig = SystemConfigUtil.productSysConfig(system);
        if (productSysConfig == null) {
            return result;
        }
        // 通过配置获取 每页显示的产品数量
        ProductSysListConfig list = productSysConfig.getList();
        if (list != null && list.getPer_page() > 1) {
            size = list.getPer_page();
        }

        // 通过系统数据，获取该系统下的所有分类数据！
        List<SCategories> listSCategories = categoryServiceImpl.getInfosByHostSiteSystemIdAndDefaultOrder(system.getHostId(), system.getSiteId(),
                system.getId());

        PageInfo<ProductDataTableForList> productSearchByHolder = searchServiceImpl.productSearchByHolder(systemId, keyword, page, size);
        StringBuilder html = hSearchProductItemListUdin.html(productSysConfig, searchSystem.getPage(), productSearchByHolder.getList(), listSCategories,
                keyword, page, searchSystem.getTotal(), size);
        result.append(AssetsResponseUtil.htmlCompress(html, false));
        return result;
    }

    private StringBuilder articleSearch(Long hostId, Long siteId, SearchSystem searchSystem, int page, int size) throws Exception {
        StringBuilder result = new StringBuilder();

        SSystem system = searchSystem.getSystem();
        Long systemId = system.getId();

        AccessPage accessPage = requestHolder.getAccessPage();
        SiteSearchPage siteSearchPage = accessPage.getSitePage().getSiteSearchPage();
        String keyword = siteSearchPage.getKeyword();

        // 获取系统配置
        ArticleSysConfig articleSysConfig = SystemConfigUtil.articleSysConfig(system);
        if (articleSysConfig == null) {
            return result;
        }
        ArticleSysListConfig list = articleSysConfig.getList();
        if (list != null && list.findPerPage() > 1) {
            size = list.findPerPage();
        }
        // 通过配置获取每页显示新闻数量 pageSize

        // 通过系统数据，获取该系统下的所有分类数据！
        List<SCategories> listSCategories = categoryServiceImpl.getInfosByHostSiteSystemIdAndDefaultOrder(system.getHostId(), system.getSiteId(),
                system.getId());

        PageInfo<Article> articleSearchByHolder = searchServiceImpl.articleSearchByHolder(systemId, keyword, page, size);

        StringBuilder html = hSearchArticleItemListUdin.html(articleSysConfig, searchSystem.getPage(), articleSearchByHolder.getList(), listSCategories,
                keyword, page, searchSystem.getTotal(), size);

        result.append(AssetsResponseUtil.htmlCompress(html, false));
        return result;
    }
}
